import re
import tkinter as tk


class LoginApp:
    def __init__(self, root):
        self.root = root
        self.root.title("登录系统")
        self.root.geometry("400x300")

        self.center_window(400, 300)
        self.setup_ui()

    def center_window(self, width, height):
        """
        将窗口居中显示
        """
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        x = (screen_width - width) // 2
        y = (screen_height - height) // 2
        self.root.geometry(f"{width}x{height}+{x}+{y}")

    def check_username(self):
        """
        用户名验证函数
        """
        username = self.entry_user.get().strip()

        if not username:
            return True
        else:
            if not re.match(r'^[a-zA-Z0-9_-]{4,16}$', username):
                self.lbl_username_error.config(text='用户名格式不正确', fg='red')
                return False
            else:
                self.lbl_username_error.config(text='')
                return True

    def login(self):
        """
        登录功能
        """
        str_username = self.entry_user.get().strip()
        str_password = self.entry_password.get().strip()

        if str_username == 'admin' and str_password == '123456':
            print("登录成功")
        else:
            print("用户名或密码错误")

    def setup_ui(self):
        """
        设置用户界面
        """
        # 创建主框架
        frame_main = tk.Frame(self.root, padx=20, pady=20)
        frame_main.pack(pady=20)

        # 用户名区域
        lbl_username = tk.Label(frame_main, text="用户名:")
        lbl_username.grid(row=0, column=0, sticky='w', padx=(0, 10))

        self.entry_user = tk.Entry(frame_main, validate="focusout",
                                   validatecommand=self.check_username)
        self.entry_user.grid(row=0, column=1)

        self.lbl_username_error = tk.Label(frame_main, text="", fg="red")
        self.lbl_username_error.grid(row=0, column=2, sticky='w', padx=(10, 0))

        # 密码区域
        lbl_password = tk.Label(frame_main, text="密码:")
        lbl_password.grid(row=1, column=0, sticky='w', padx=(0, 10), pady=(10, 0))

        self.entry_password = tk.Entry(frame_main, show="*")
        self.entry_password.grid(row=1, column=1, pady=(10, 0))

        # 按钮区域
        frame_buttons = tk.Frame(self.root)
        frame_buttons.pack(pady=20)

        btn_login = tk.Button(frame_buttons, text="登录",
                              command=self.login, width=10)
        btn_login.pack(side='left', padx=(0, 10))

        btn_cancel = tk.Button(frame_buttons, text="退出",
                               command=self.root.quit, width=10)
        btn_cancel.pack(side='left')


# === 主程序 ===
if __name__ == "__main__":
    root = tk.Tk()
    app = LoginApp(root)
    root.mainloop()